#include "mainwidget.h"
#include "ui_mainwidget.h"
#include <QFileDialog>
#include <QFile>
#include <QCoreApplication>
#include <QDebug>

MainWidget::MainWidget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::MainWidget)
    , m_player(new QMediaPlayer(this))
{
    ui->setupUi(this);
    ui->voices->addItem("zh-CN-XiaoxiaoNeural");
    ui->voices->addItem("zh-CN-XiaoyiNeural");
    ui->voices->addItem("zh-CN-YunjianNeural");
    ui->voices->addItem("zh-CN-YunxiNeural");
    ui->voices->addItem("zh-CN-YunxiaNeural");
    ui->voices->addItem("zh-CN-YunyangNeural");
    ui->voices->addItem("zh-CN-liaoning-XiaobeiNeural");
    ui->voices->addItem("zh-CN-shaanxi-XiaoniNeural");
    ui->voices->addItem("zh-HK-HiuGaaiNeural");
    ui->voices->addItem("zh-HK-HiuMaanNeural");
    ui->voices->addItem("zh-HK-WanLungNeural");
    ui->voices->addItem("zh-TW-HsiaoChenNeural");
    ui->voices->addItem("zh-TW-HsiaoYuNeural");
    ui->voices->addItem("zh-TW-YunJheNeural");

    m_toolsDir = QCoreApplication::applicationDirPath() + "/tools";
    m_tmpDir = QCoreApplication::applicationDirPath() + "/tmp";
    QDir(m_toolsDir).mkpath(".");
    QDir(m_tmpDir).mkpath(".");

    connect(&m_listVoicesProcess, SIGNAL(finished(int)), this, SLOT(onListVoicesProcessFinished()));
    m_listVoicesProcess.start(m_toolsDir + "/edge-tts.exe", {"--list-voices"});

    QString edgettsFileName = m_toolsDir + "/edge-tts.exe";
    if (!QFile::exists(edgettsFileName)) {
        QFile file(":/tools/edge-tts.exe");
        QFile outFile(edgettsFileName);
        if (file.open(QIODevice::ReadOnly) && outFile.open(QIODevice::WriteOnly)) {
            outFile.write(file.readAll());
        }
    }
}

MainWidget::~MainWidget()
{
    delete ui;
}


void MainWidget::on_loadFile_clicked()
{
    QString fileName = QFileDialog::getOpenFileName(this, "选择文本文件");
    if (fileName.isEmpty()) {
        return;
    }

    QFile file(fileName);
    if (file.open(QIODevice::Text | QIODevice::ReadOnly)) {
        ui->textEdit->setPlainText(QString::fromUtf8(file.readAll()));
    }
}

void MainWidget::on_listen_clicked()
{
    QString tmpFile(m_tmpDir + "/tmp.mp3");

    if (QFile::exists(tmpFile)) {
        QFile::remove(tmpFile);
    }

    QStringList arguments;
    arguments << "--voice" << ui->voices->currentText();
    arguments << "--text" << ui->textEdit->toPlainText().left(50);
    arguments << "--write-media" << tmpFile;
    QProcess::execute(m_toolsDir + "/edge-tts.exe", arguments);

    m_player->stop();
    m_player->setMedia(QUrl(""));
    m_player->setMedia(QUrl::fromLocalFile(tmpFile));
    m_player->play();
}


void MainWidget::on_saveTo_clicked()
{
    QString fileName = QFileDialog::getSaveFileName(this, "选择MP3存储位置", "", "MP3 (*.mp3)");
    if (fileName.isEmpty()) {
        return;
    }

    if (QFile::exists(fileName)) {
        QFile::remove(fileName);
    }

    QStringList arguments;
    arguments << "--voice" << ui->voices->currentText();
    arguments << "--text" << ui->textEdit->toPlainText();
    arguments << "--write-media" << fileName;
    QProcess::startDetached(m_toolsDir + "/edge-tts.exe", arguments);
}

void MainWidget::onListVoicesProcessFinished()
{
    QString output = m_listVoicesProcess.readAllStandardOutput();
    if (output.isEmpty()) {
        return;
    }

    QStringList zhVoices;
    QStringList otherVoices;

    output.replace("\r", "");
    QStringList voices = output.split("\n\n", Qt::SkipEmptyParts);
    for (int i=0; i<voices.size(); ++i) {
        QStringList parts = voices[i].split("\n");
        if (parts.size() < 2) {
            continue;
        }

        QString name = parts[0].split(":")[1].trimmed();
        QString gender = parts[1].split(":")[1].trimmed();
        qDebug() << name << gender;

        if (name.startsWith("zh")) {
            zhVoices.append(name);
        } else {
            otherVoices.append(name);
        }
    }

    ui->voices->clear();
    ui->voices->addItems(zhVoices + otherVoices);
}

